﻿#include "mainwindow.h"
#include "ui_mainwindow.h"

MainWindow::MainWindow(QWidget *parent)
    : QMainWindow(parent)
    , ui(new Ui::MainWindow)
{
    myserialPort = new QSerialPort(this);
    connect(myserialPort, SIGNAL(readyRead()), this, SLOT(slot_serialPortRead()));
    ui->setupUi(this);
}

MainWindow::~MainWindow()
{
    delete myserialPort;
    delete ui;
}

// 关闭COM
void MainWindow::slot_PButton_COM()
{
    if(myserialPort->isOpen())
    {
        myserialPort->close();
    }
    ui->label_COM_Info->setText("COM?");
    ui->label_Fre_Data->setText("0");
    ui->label_DC_Data->setText("0");
    ui->label_PW_Data->setText("0");
    ui->comboBox_COM->clear();
    ui->comboBox_COM->addItem("choose one");
    ui->comboBox_COM->setEnabled(true);
}

// 下拉框选择COM打开
void MainWindow::slot_comboBox_COM()
{
    QString spTxt = ui->comboBox_COM->currentText();
//    qDebug() << spTxt;

    if(spTxt == "")
    {
        return;
    }
    else
    {
//        spTxt = spTxt.section(':', 0, 0);

        if(!myserialPort->isOpen())
        {
            myserialPort->setBaudRate(QSerialPort::Baud115200);
            myserialPort->setDataBits(QSerialPort::Data8);
            myserialPort->setStopBits(QSerialPort::OneStop);
            myserialPort->setParity(QSerialPort::NoParity);
            myserialPort->setPortName(spTxt);

            myserialPort->open(QIODevice::ReadOnly);
            if(myserialPort->isOpen())
            {
                ui->label_COM_Info->setText(spTxt+"_on");
                ui->comboBox_COM->setEnabled(false);
            }
        }
    }
}

// 串口数据接收
void MainWindow::slot_serialPortRead()
{
    QByteArray recBuf;
    int tmp_int;

    recBuf = myserialPort->readAll();
    qDebug() << recBuf.toHex();

    tmp_int  = recBuf.at(8)  & 0x000000FF;
    tmp_int |= (recBuf.at(9)  << 8 )  & 0x0000FF00;
    tmp_int |= (recBuf.at(10) << 16) & 0x00FF0000;
    tmp_int |= (recBuf.at(11) << 24) & 0xFF000000;
    ui->label_Fre_Data->setText(QString::number(tmp_int));

    tmp_int  = recBuf.at(4)  & 0x000000FF;
    tmp_int |= (recBuf.at(5) << 8 )  & 0x0000FF00;
    tmp_int |= (recBuf.at(6) << 16) & 0x00FF0000;
    tmp_int |= (recBuf.at(7) << 24) & 0xFF000000;
    ui->label_PW_Data->setText(QString::number(tmp_int));

    tmp_int  = recBuf.at(0)  & 0x000000FF;
    tmp_int |= (recBuf.at(1) << 8 ) & 0x0000FF00;
    tmp_int |= (recBuf.at(2) << 16) & 0x00FF0000;
    tmp_int |= (recBuf.at(3) << 24) & 0xFF000000;
    ui->label_DC_Data->setText(QString::number(tmp_int/100.0));
}
